package com.realife.eson.common.util.common;


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * StreamUtil类
 *
 * @author zgc
 */
public class StreamUtil {


    /**
     * @param inStream
     * @param encoding
     * @return
     */
    public static String stream2String(InputStream inStream, String encoding) {
        int _buffer_size = 1024;
        String result = null;
        try {
            if (inStream != null) {
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                byte[] tempBytes = new byte[_buffer_size];
                int count = -1;
                while ((count = inStream.read(tempBytes, 0, _buffer_size)) != -1) {
                    outStream.write(tempBytes, 0, count);
                }
                tempBytes = null;
                outStream.flush();
                result = new String(outStream.toByteArray(), encoding);
            }
        } catch (Exception e) {
            result = null;
        }
        return result;
    }


    /**
     * 功能：将输入流转换成byte[]， 即可以把文件的内容读入到byte[]
     *
     * @param is
     * @return
     * @throws Exception
     */
    public static byte[] streamToByteArray(InputStream is) {
        ByteArrayOutputStream bos = null;
        byte[] array = null;
        try {
            bos = new ByteArrayOutputStream();//创建输出流对象
            byte[] b = new byte[1024];//字节数组
            int len;
            while ((len = is.read(b)) != -1) {//循环读取
                bos.write(b, 0, len);//把读取到的数据，写入bos
            }
            array = bos.toByteArray();//然后将bos 转成字节数组
        } catch (Exception e) {

        } finally {
            ResourcesCloseUtils.close(bos);
        }
        return array;
    }


    /**
     * 功能：将InputStream转换成String
     *
     * @param is
     * @return
     * @throws Exception
     */
    public static StringBuilder streamToString(InputStream is) {
        BufferedReader reader = null;
        StringBuilder builder = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is));
            builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line + "\r\n");
            }
        } catch (Exception e) {

        } finally {
            ResourcesCloseUtils.close(reader);
        }
        return builder;
    }

}
